package com.amos.wx.mp;

import com.amos.wx.mp.config.WeChatMpProperties;
import com.amos.wx.mp.controller.WeChatCallBackController;
import com.amos.wx.mp.handler.DefaultMessageHandlerFactory;
import com.amos.wx.mp.handler.MessageHandlerFactory;
import com.amos.wx.mp.http.WeChatApiRequest;
import com.amos.wx.mp.service.AccessTokenService;
import com.amos.wx.mp.store.InMemoryTokenStore;
import com.amos.wx.mp.store.TokenStore;
import com.amos.wx.mp.support.DefaultMessageDispatcher;
import com.amos.wx.mp.support.MessageDispatcher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author amos
 */
@Configuration
@EnableConfigurationProperties(WeChatMpProperties.class)
public class WeChatMpAutoConfiguration {

    /*@Bean
    public WeChatCallBackController weChatCallBackController() {
        return new WeChatCallBackController();
    }*/

    @Bean
    @ConditionalOnMissingBean(MessageDispatcher.class)
    public MessageDispatcher messageDispatcher(MessageHandlerFactory messageHandlerFactory,
                                               ApplicationContext applicationContext) {
        return new DefaultMessageDispatcher(messageHandlerFactory, applicationContext);
    }

    @Bean
    public AccessTokenService accessTokenService(TokenStore tokenStore,
                                                 WeChatApiRequest weChatApiRequest, WeChatMpProperties mpProperties) {
        return new AccessTokenService(tokenStore, weChatApiRequest, mpProperties);
    }

    @Bean
    public WeChatApiRequest weChatApiRequest(RestTemplate restTemplate, WeChatMpProperties mpProperties) {
        return new WeChatApiRequest(restTemplate, mpProperties);
    }

    @Bean
    @ConditionalOnMissingBean(MessageHandlerFactory.class)
    public MessageHandlerFactory messageHandlerFactory() {
        return new DefaultMessageHandlerFactory();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}
